/**
 * 测试用例模板格式化工具
 */

/**
 * 将测试用例数据格式化为模板文本
 */
export function formatTestCaseToTemplate(data: {
  description?: string
  preconditions?: string
  test_steps?: Array<{ step_number: number; action: string; expected_result: string }>
  expected_result?: string
  postconditions?: string
}): string {
  const sections: string[] = []

  // 测试用例描述
  if (data.description) {
    sections.push(`<h2>测试用例描述</h2>`)
    sections.push(`<div>${data.description}</div>`)
  } else {
    sections.push(`<h2>测试用例描述</h2>`)
    sections.push(`<div><p>请在此处填写测试用例的描述信息...</p></div>`)
  }

  // 前置条件
  sections.push(`<h2>前置条件</h2>`)
  if (data.preconditions) {
    sections.push(`<div>${data.preconditions}</div>`)
  } else {
    sections.push(`<div><p>请在此处填写测试的前置条件，如：环境要求、数据准备等...</p></div>`)
  }

  // 测试步骤
  sections.push(`<h2>测试步骤</h2>`)
  if (data.test_steps && data.test_steps.length > 0) {
    data.test_steps.forEach((step, index) => {
      sections.push(`<h3>步骤 ${step.step_number || index + 1}</h3>`)
      sections.push(`<p><strong>操作：</strong>${step.action || '请填写操作步骤'}</p>`)
      sections.push(`<p><strong>预期结果：</strong>${step.expected_result || '请填写预期结果'}</p>`)
    })
  } else {
    sections.push(`<div><p>请按以下格式添加测试步骤：</p>`)
    sections.push(`<h3>步骤 1</h3>`)
    sections.push(`<p><strong>操作：</strong>请填写操作步骤</p>`)
    sections.push(`<p><strong>预期结果：</strong>请填写预期结果</p></div>`)
  }

  // 预期结果（整体）
  sections.push(`<h2>预期结果（整体）</h2>`)
  if (data.expected_result) {
    sections.push(`<div>${data.expected_result}</div>`)
  } else {
    sections.push(`<div><p>请在此处填写整体预期结果...</p></div>`)
  }

  // 后置条件
  sections.push(`<h2>后置条件</h2>`)
  if (data.postconditions) {
    sections.push(`<div>${data.postconditions}</div>`)
  } else {
    sections.push(`<div><p>请在此处填写测试的后置条件，如：数据清理、环境恢复等...</p></div>`)
  }

  return sections.join('\n')
}

/**
 * 从模板文本中解析出测试用例数据
 */
export function parseTemplateToTestCase(htmlContent: string): {
  description?: string
  preconditions?: string
  test_steps: Array<{ step_number: number; action: string; expected_result: string }>
  expected_result?: string
  postconditions?: string
} {
  // 创建临时DOM来解析HTML
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = htmlContent

  const result: {
    description?: string
    preconditions?: string
    test_steps: Array<{ step_number: number; action: string; expected_result: string }>
    expected_result?: string
    postconditions?: string
  } = {
    test_steps: []
  }

  // 按h2标题分割内容
  const sections = htmlContent.split(/<h2[^>]*>/i)
  
  sections.forEach(section => {
    if (!section.trim()) return

    // 提取标题和内容
    const match = section.match(/^([^<]+)<\/h2>(.*)$/is)
    if (!match) return

    const title = match[1].trim()
    let content = match[2].trim()

    // 移除提示文本（包含"请在此处填写"或"请填写"的内容）
    content = content.replace(/<p>请[^<]*?<\/p>/gi, '')
    content = content.replace(/<div><p>请[^<]*?<\/p><\/div>/gi, '')
    content = content.trim()

    if (title === '测试用例描述') {
      if (content && !content.includes('请在此处填写')) {
        result.description = content
      }
    } else if (title === '前置条件') {
      if (content && !content.includes('请在此处填写')) {
        result.preconditions = content
      }
    } else if (title === '测试步骤') {
      // 解析测试步骤
      const stepSections = content.split(/<h3[^>]*>/i)
      let stepNumber = 1

      stepSections.forEach(stepSection => {
        if (!stepSection.trim()) return

        const stepMatch = stepSection.match(/^步骤\s*(\d+)[^<]*<\/h3>(.*)$/is)
        if (!stepMatch) {
          // 可能没有步骤编号，尝试直接解析
          const actionMatch = stepSection.match(/<p><strong>操作：<\/strong>([^<]*)<\/p>/i)
          const expectedMatch = stepSection.match(/<p><strong>预期结果：<\/strong>([^<]*)<\/p>/i)
          
          if (actionMatch || expectedMatch) {
            const action = actionMatch ? actionMatch[1].trim() : ''
            const expected = expectedMatch ? expectedMatch[1].trim() : ''
            
            // 跳过提示文本
            if (action && !action.includes('请填写') && expected && !expected.includes('请填写')) {
              result.test_steps.push({
                step_number: stepNumber++,
                action: action,
                expected_result: expected
              })
            }
          }
        } else {
          const num = parseInt(stepMatch[1])
          const stepContent = stepMatch[2]
          
          const actionMatch = stepContent.match(/<p><strong>操作：<\/strong>([^<]*)<\/p>/i)
          const expectedMatch = stepContent.match(/<p><strong>预期结果：<\/strong>([^<]*)<\/p>/i)
          
          if (actionMatch || expectedMatch) {
            const action = actionMatch ? actionMatch[1].trim() : ''
            const expected = expectedMatch ? expectedMatch[1].trim() : ''
            
            // 跳过提示文本
            if (action && !action.includes('请填写') && expected && !expected.includes('请填写')) {
              result.test_steps.push({
                step_number: num,
                action: action,
                expected_result: expected
              })
            }
          }
        }
      })
    } else if (title === '预期结果（整体）') {
      if (content && !content.includes('请在此处填写')) {
        result.expected_result = content
      }
    } else if (title === '后置条件') {
      if (content && !content.includes('请在此处填写')) {
        result.postconditions = content
      }
    }
  })

  // 如果没有解析到步骤，尝试更宽松的解析方式
  if (result.test_steps.length === 0) {
    const stepPattern = /(?:步骤\s*\d+[^<]*<\/h3>|<h3[^>]*>步骤\s*\d+[^<]*<\/h3>)[\s\S]*?<p><strong>操作：<\/strong>([^<]+)<\/p>[\s\S]*?<p><strong>预期结果：<\/strong>([^<]+)<\/p>/gi
    let match
    let stepNum = 1
    while ((match = stepPattern.exec(htmlContent)) !== null) {
      const action = match[1].trim()
      const expected = match[2].trim()
      if (action && expected && !action.includes('请填写') && !expected.includes('请填写')) {
        result.test_steps.push({
          step_number: stepNum++,
          action: action,
          expected_result: expected
        })
      }
    }
  }

  // 确保步骤编号正确
  result.test_steps.forEach((step, index) => {
    step.step_number = index + 1
  })

  return result
}

